<!--
 * @Author: master
 * @Date: 2022-04-04 16:50:57
 * @LastEditTime: 2022-04-06 17:19:14
 * @Description: 菜单
-->
<script lang="jsx">
import { ref, defineComponent, compile, h, computed } from 'vue';
import { useRouter } from 'vue-router';
import { listenerRouteChange } from '@path/router/route-listener.js'; // 路由监听
export default defineComponent({
  setup(props, { emit }) {
    // 当前选中的menu
    const selectedKey = ref();
    const router = useRouter();
    /**
     * 获取layout下的路由
     */
    const getRoutes = computed(() => {
      return [router.getRoutes().find(el => el.name === 'layout')];
    });
    /**
     * 路由跳转
     */
    const goto = elem => {
      router.push({ name: elem.name });
    };
    /**
     * 折叠状态
     */
    const onCollapse = val => {
      emit('setCollapsed', val);
    };
    /**
     * 监听路由变化
     */
    listenerRouteChange(route => {
      selectedKey.value = [route.name];
    });
    /**
     * sub menu 渲染
     */
    const renderSubMenu = () => {
      const nodes = [];
      getRoutes.value.forEach(element => {
        const icon = element?.meta?.icon ? `<${element.meta.icon}/>` : ``;
        const r = (
          <a-sub-menu
            key={element?.name}
            v-slots={{
              icon: () => h(compile(icon)),
              title: () => h(compile(element?.meta?.title)),
            }}
          >
            {element?.children?.map(elem => {
              return (
                <a-menu-item key={elem?.name} onClick={() => goto(elem)}>
                  {elem?.meta?.title}
                </a-menu-item>
              );
            })}
          </a-sub-menu>
        );
        nodes.push(r);
      });
      return nodes;
    };
    return () => (
      <a-menu
        style="height: 100%"
        selected-keys={selectedKey.value}
        auto-open-selected={true}
        show-collapse-button
        breakpoint="xl"
        onCollapse={onCollapse}
      >
        {renderSubMenu()}
      </a-menu>
    );
  },
});
</script>
